package cn.johnyu.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import java.util.concurrent.Executor;

public class ConfigClientDemo {
    private static final Logger logger= LoggerFactory.getLogger(ConfigClientDemo.class);
    public static void main(String[] args) {
        try {
            String serverAddr = "http://localhost:8848";
            String dataId = "test_cfg1";
            String group = "DEFAULT_GROUP";
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            properties.put("username", "nacos");
            properties.put("password", "nacos");
            properties.put("namespace","");//namespace = '' 表示public，但不可以写成public
            ConfigService configService = NacosFactory.createConfigService(properties);
            //添加（更新）一条配置信息
            configService.publishConfig(dataId,group,"这是一条配置");
            //获取配置信息
            String content = configService.getConfig(dataId, group, 10000);
            logger.info(content);
            //此时可以在nacos控制台中修改配置文件。。。
            configService.addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }
                @Override
                public void receiveConfigInfo(String s) {
                    logger.info(s);
                }
            });
            //main 线程停止，会导致监听线程一并结束，需要阻塞主线程，也可：System.in.read();
            Thread.currentThread().join();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}
